<?php

namespace app\common\cachemodel\name_analyze;

use app\common\lib\Util;
use app\common\model\BaseCache;
use traits\model\SoftDelete;
use XznsTools\cache\CacheManage;

class Zl9NameAnalyzeCreateNameRecord extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl9_name_analyze_create_name_record';

    protected $cacheModel = 'name_analyze.create_name_record';

    use SoftDelete;

    private $wuxingAttrColor = [ // 五行属性颜色
        '木' => [
            'color' => '#24252A',
            'bg_color' => '#5BBB87',
            'bg_border_color' => '#5BBB87',
        ],
        '火' => [
            'color' => '#24252A',
            'bg_color' => '#EC8337',
            'bg_border_color' => '#EC8337',
        ],
        '土' => [
            'color' => '#24252A',
            'bg_color' => '#C5C0C0',
            'bg_border_color' => '#C5C0C0',
        ],
        '金' => [
            'color' => '#24252A',
            'bg_color' => '#FDC756',
            'bg_border_color' => '#FDC756',
        ],
        '水' => [
            'color' => '#24252A',
            'bg_color' => '#5F7CEE',
            'bg_border_color' => '#5F7CEE',
        ],
    ];

    /**
     * 写入信息
     * @param array $data
     * @return int
     */
    public function SaveData(array $data)
    {
        try
        {
            if (isset($data['params']) && is_array($data['params']))
            {
                $data['params'] = json_encode($data['params'], JSON_UNESCAPED_UNICODE);
            }
            if (isset($data['content']) && is_array($data['content']))
            {
                $data['content'] = json_encode($data['content'], JSON_UNESCAPED_UNICODE);
            }
            $id = $this->insertGetId($data);
            if (isset($data['status']) && $data['status'] > 0)
            {
                $this->listDataAdd($data['uid'], [$id => $id]);
            }
            return (int)$id;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return 0;
        }
    }

    /**
     * 更新信息
     * @param int $id
     * @param int $uid
     * @param array $data
     * @return bool
     */
    public function UpdateData(int $id, int $uid, array $data)
    {
        try
        {
            if (isset($data['params']) && is_array($data['params']))
            {
                $data['params'] = json_encode($data['params'], JSON_UNESCAPED_UNICODE);
            }
            if (isset($data['content']) && is_array($data['content']))
            {
                $data['content'] = json_encode($data['content'], JSON_UNESCAPED_UNICODE);
            }
            $this->where(['id' => $id])->update($data);
            if (isset($data['status']) && $data['status'])
            {
                $this->listDataAdd($uid, [$id => $id]);
            }
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->setCacheTime(5)->setCache($data);
            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }

    /**
     * 解锁数据
     * @param int $id
     * @param int $unlockType 解锁方式 1=>微信 2=>支付宝 3=>准币
     * @param string $orderNum
     * @return bool
     */
    public function unlockData(int $id, int $unlockType, string $orderNum)
    {
        try
        {
            $info = $this->getInfoById($id);
            $nowTime = time();
            $data = [
                'status' => 1,
                'unlock_type' => $unlockType,
                'order_num' => $orderNum,
                'pay_time' => $nowTime,
                'start_time' => $nowTime,
                'update_time' => $nowTime,
            ];
            $res = $this->UpdateData($id, $info['uid'], $data);
            if ($res)
            {
                //  八字起名 队列添加
                Util::queuePush('name_analyze_create_name', ['id' => $id]);

                return true;
            }
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
        }
        return false;
    }

    /**
     * @param array $ids
     * @param array|null $type
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        if ($ids)
        {   // 获取未删除 的数据
            $where = ['id' => ['in', $ids]];
        } else
        {   // 获取指定pid  未删除 且 未隐藏的数据
            $where = ['uid' => $type[0]];
        }
        $field = 'uid,type,status,params,unlock_type,order_num,content,pay_time,start_time,success_time,create_time,update_time';
        try
        {
            $data = $this->field($field)
                ->where($where)
                ->column($field, 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'uid', 'type', 'status', 'unlock_type', 'pay_time', 'create_time', 'update_time', 'start_time', 'success_time']);
            if (isset($itemData['content']))
            {
                $data[$index]['content'] = $itemData['content'] ? json_decode($itemData['content'], true) : [];
            }
            if (isset($itemData['params']))
            {
                $data[$index]['params'] = $itemData['params'] ? json_decode($itemData['params'], true) : [];
            }
        }
        return $data;
    }

    /**
     * @param int $uid
     * @param int $page
     * @param int $limit
     * @return array
     * @throws \Exception
     */
    public function pageDataIds(int $uid, int $page, int $limit)
    {
        $resData = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, $uid)
            ->setPage($page)
            ->setPageSize($limit)
            ->setSort('desc')
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($uid)
            {
                try
                {
                    $data = $this->where(['uid' => $uid, 'status' => ['>', 0]])->order("id {$sortType}")->column('id');
                    $resData = [];
                    foreach ($data as $id)
                    {
                        $resData[$id] = ['id' => $id];
                    }
                    return $resData;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'id', 0);
        if ($resData['data'])
        {
            $resData['data'] = array_map('intval', array_keys($resData['data']));
        }
        return $resData;
    }

    public function getPageListData(int $uid, int $page, int $pageSize = 15)
    {
        $pageData = $this->pageDataIds($uid, $page, $pageSize);

        $data = $pageData['data'] ? $this->batchGetInfoByIds($pageData['data']) : [];
        $nowTime = time();
        $dataList = [];
        foreach ($pageData['data'] as $id)
        {
            if (!isset($data[$id]))
            {
                continue;
            }
            $dataItem = $data[$id];
            if ($dataItem['type'] === 1)
            {
                $list = [sprintf("档案： %s %s", $dataItem['params']['recode_birth_date'] ?? '', $dataItem['params']['recode_birth_time'] ?? '')];
            } else
            {
                $originatorData1 = current($dataItem['params']['originator_data']);
                $list = [sprintf("档案： %s %s", $originatorData1['birth_date'] ?? '', $originatorData1['birth_time'] ?? '')];
            }
            switch ($dataItem['unlock_type'])
            {
                case 1:
                    $list[] = '支付类型：微信支付';
                    break;
                case 2:
                    $list[] = '支付类型：支付宝支付';
                    break;
                case 3:
                    $list[] = '支付类型：准币';
                    break;
                default:
            }
            if ($dataItem['status'] === 2)
            {
                if ($dataItem['type'] === 1)
                {
                    $names = $dataItem['content']['ys_name_result']['list'][0]['names'] ?? '';
                    $namesArr = array_column($names, 'text');
                    $title = sprintf("名字推荐：%s...", implode('', $namesArr));
                } else
                {
                    $title = sprintf("名字推荐：%s...", $dataItem['content']['business_recommend'][0]['name_txt']);
                }
            } else
            {
                $title = '名字推荐：***';
                // 计算中
                if ($nowTime - $dataItem['start_time'] > 300)
                {   //  长时间 计算失败 重新计算
                    $this->UpdateData($dataItem['id'], $dataItem['uid'], ['status' => 1, 'start_time' => $nowTime]);
                    Util::queuePush('name_analyze_create_name', ['id' => $id]);
                }
            }

            $dataList[] = [
                'id' => $dataItem['id'],
                'create_time' => date('Y.m.d H:i', $dataItem['pay_time']),
                'title' => $title,
                'score_desc' => '',
                'type' => 2,
                'list' => $list,
                'right_desc' => $dataItem['type'] === 1 ? '个人起名' : '公司起名',
            ];
        }
        $pageData['data'] = $dataList;

        return $pageData;
    }

    /**
     * 个人起名 数据重组
     * @param array $data
     * @return array
     */
    public function dataResertPersonal(array $data)
    {
        $wuxingbili = $data['content']['wuxing_data']['wuxingbili'];
        $patternList = [];
        foreach ($data['content']['wuxing_data']['pattern'] as $datum)
        {
            $patternList[] = [
                'name' => $datum,
                'color' => '#EE904B',
                'bg_color' => '#FFF9F3',
                'bg_border_color' => '#F9CEA4',
            ];
        }
        $personalData = [
            'wuxing_list' => [
                ['name' => '金', 'color' => '#FDC756', 'score' => $wuxingbili['金'],],
                ['name' => '木', 'color' => '#5BBB87', 'score' => $wuxingbili['木'],],
                ['name' => '水', 'color' => '#5F7CEE', 'score' => $wuxingbili['水'],],
                ['name' => '火', 'color' => '#EC8337', 'score' => $wuxingbili['火'],],
                ['name' => '土', 'color' => '#DF9F4E', 'score' => $wuxingbili['土'],],
            ],
            'tags_list' => [
                [
                    'name' => '喜用神：',
                    'tag_list' => [
                        [
                            'name' => $data['content']['wuxing_data']['yongshen'],
                            'color' => $this->wuxingAttrColor[$data['content']['wuxing_data']['quming']]['color'],
                            'bg_color' => $this->wuxingAttrColor[$data['content']['wuxing_data']['quming']]['bg_color'],
                            'bg_border_color' => $this->wuxingAttrColor[$data['content']['wuxing_data']['quming']]['bg_border_color'],
                        ],
                    ],
                ], [
                    'name' => '整体格局：',
                    'tag_list' => $patternList,
                ],
            ],
            'data_list' => [],
            'is_special_demand' => 0,
        ];
        $status = $data['status'] === 2 ? 2 : 1;
        if ($status === 2)
        {
            $dataList = [
                [   //  侧重用神推荐
                    'title' => '侧重用神推荐',
                    'list' => $data['content']['ys_name_result']['list'],
                    'desc' => $data['content']['ys_name_result']['desc'],   //  综合分析-内容
                    'icon' => '/test/name_analyze/tip_icon1.png',   //  综合分析-图标
                    'name' => '综合分析',   //  综合分析-名字
                ],
                [   //  侧重格局推荐
                    'title' => '侧重格局推荐',
                    'list' => $data['content']['gj_name_result']['list'],
                    'desc' => $data['content']['gj_name_result']['desc'],   //  综合分析-内容
                    'icon' => '/test/name_analyze/tip_icon1.png',   //  综合分析-图标
                    'name' => '综合分析',   //  综合分析-名字
                ],
            ];
            if (isset($data['content']['tsyq_name_result']) && $data['content']['tsyq_name_result'])
            {
                $dataList[] = [ //  综合特殊要求AI推荐
                    'title' => '综合特殊要求AI推荐',
                    'list' => $data['content']['tsyq_name_result']['list'],
                    'desc' => $data['content']['tsyq_name_result']['desc'],   //  综合分析-内容
                    'icon' => '/test/name_analyze/tip_icon1.png',   //  综合分析-图标
                    'name' => '综合分析',   //  综合分析-名字
                ];
                $isSpecialDemand = 1;
            } else
            {
                $isSpecialDemand = 0;
            }
            $personalData['data_list'] = $dataList;
            $personalData['is_special_demand'] = $isSpecialDemand;
        } else
        {
            $btnData = [
                'name' => '计算中（预计2分钟）…',
                'target' => 'local',
                'link' => 'empty',
            ];

            $nowTime = time();
            // 计算中
            if ($nowTime - $data['start_time'] > 300)
            {   //  长时间 计算失败 重新计算
                $this->UpdateData($data['id'], $data['uid'], ['status' => 1, 'start_time' => $nowTime]);
                Util::queuePush('name_analyze_create_name', ['id' => $data['id']]);
            }
        }

        return [
            'personal_data' => $personalData,
            'type' => 1,
            'company_data' => null,
            'btn_data' => $btnData ?? null,
            'status' => $status,
            'unlock_data' => $this->getUnlockDataPersonal($data['params']),
        ];
    }

    /**
     * 公司起名 数据重组
     * @param array $data
     * @return array
     */
    public function dataResertCompany(array $data)
    {
        $headerTabs = [];
        $originatorNum = count($data['params']['originator_data']);
        $ridNum = $originatorNum;
        for ($i = 0; $i <= $ridNum; $i++)
        {
            if ($i === 0)
            {
                $title = '公司';
                $rid = $data['params']['company_rid'];
                $tip = '五行比例';
            } else
            {
                $title = '创始人' . $originatorNum;
                $originatorNum--;
                $rid = $data['params']['originator_data'][$originatorNum]['rid'];
                $tip = "（{$data['params']['originator_data'][$originatorNum]['name']}）五行比例";
            }
            $wuxingData = $data['content']['wuxing_data'][$rid];
            $patternList = [];
            foreach ($wuxingData['pattern'] as $datum)
            {
                $patternList[] = [
                    'name' => $datum,
                    'color' => '#EE904B',
                    'bg_color' => '#FFF9F3',
                    'bg_border_color' => '#F9CEA4',
                ];
            }
            $headerTabs[] = [
                'title' => $title,
                'tip' => $tip,
                'wuxing_list' => [
                    ['name' => '金', 'color' => '#FDC756', 'score' => $wuxingData['wuxingbili']['金'],],
                    ['name' => '木', 'color' => '#5BBB87', 'score' => $wuxingData['wuxingbili']['木'],],
                    ['name' => '水', 'color' => '#5F7CEE', 'score' => $wuxingData['wuxingbili']['水'],],
                    ['name' => '火', 'color' => '#EC8337', 'score' => $wuxingData['wuxingbili']['火'],],
                    ['name' => '土', 'color' => '#DF9F4E', 'score' => $wuxingData['wuxingbili']['土'],],
                ],
                'tags_list' => [
                    [
                        'name' => '喜用神：',
                        'tag_list' => [
                            [
                                'name' => $wuxingData['yongshen'],
                                'color' => $this->wuxingAttrColor[$wuxingData['quming']]['color'],
                                'bg_color' => $this->wuxingAttrColor[$wuxingData['quming']]['bg_color'],
                                'bg_border_color' => $this->wuxingAttrColor[$wuxingData['quming']]['bg_border_color'],
                            ],
                        ],
                    ], [
                        'name' => '整体格局：',
                        'tag_list' => $patternList,
                    ],
                ],
            ];
        }
        $status = $data['status'] === 2 ? 2 : 1;
        if ($status === 2)
        {
            $professionalAnalysisList = [
                [
                    'title' => '格局分析',
                    'content' => $data['content']['pattern']['analysis'],
                    'icon' => '/test/name_analyze/tip_icon1.png',
                    'btn_name' => '查看全部解读',
                    'is_top_dotted_line' => 0,
                ], [
                    'title' => '影响',
                    'content' => $data['content']['pattern']['effect'],
                    'icon' => '/test/name_analyze/tip_icon2.png',
                    'btn_name' => '',
                    'is_top_dotted_line' => 0,
                ], [
                    'title' => '建议',
                    'content' => $data['content']['pattern']['recommend'],
                    'icon' => '/test/name_analyze/tip_icon3.png',
                    'btn_name' => '',
                    'is_top_dotted_line' => 0,
                ], [
                    'title' => '喜用神分析',
                    'content' => $data['content']['joyful_god']['analysis'],
                    'icon' => '/test/name_analyze/tip_icon1.png',
                    'btn_name' => '查看全部解读',
                    'is_top_dotted_line' => 1,
                ], [
                    'title' => '影响',
                    'content' => $data['content']['joyful_god']['effect'],
                    'icon' => '/test/name_analyze/tip_icon2.png',
                    'btn_name' => '',
                    'is_top_dotted_line' => 0,
                ], [
                    'title' => '建议',
                    'content' => $data['content']['joyful_god']['recommend'],
                    'icon' => '/test/name_analyze/tip_icon3.png',
                    'btn_name' => '',
                    'is_top_dotted_line' => 0,
                ],
            ];

            $businessRecommend = [];
            foreach ($data['content']['business_recommend'] as $k => $businessRecommendItem)
            {
                $n = $k + 1;
                $title = sprintf('推荐%s：%s', (new Util())->n2c($n), $businessRecommendItem['name_txt']);
                $businessRecommend[] = [
                    'names' => $businessRecommendItem['names'],
                    'icon' => '/test/name_analyze/tip_icon1.png',
                    'title' => $title,
                    'content' => $businessRecommendItem['content'],
                ];
            }
            $individualRecommend = [];
            foreach ($data['content']['individual_recommend'] as $k => $individualRecommendItem)
            {
                $n = $k + 1;
                $title = sprintf('推荐%s：%s', (new Util())->n2c($n), $individualRecommendItem['name_txt']);
                $individualRecommend[] = [
                    'names' => $individualRecommendItem['names'],
                    'icon' => '/test/name_analyze/tip_icon1.png',
                    'title' => $title,
                    'content' => $individualRecommendItem['content'],
                ];
            }
            $nameRecommendList = [
                [
                    'title' => '侧重主营业务',
                    'list' => $businessRecommend,
                ],
                [
                    'title' => '侧重特殊要求',
                    'list' => $individualRecommend,
                ],
            ];

            $analysisDesc = $data['content']['summarize'] ?? '';
        } else
        {
            $btnData = [
                'name' => '计算中（预计2分钟）…',
                'target' => 'local',
                'link' => 'empty',
            ];
            $nowTime = time();
            // 计算中
            if ($nowTime - $data['start_time'] > 300)
            {   //  长时间 计算失败 重新计算
                $this->UpdateData($data['id'], $data['uid'], ['status' => 1, 'start_time' => $nowTime]);
                Util::queuePush('name_analyze_create_name', ['id' => $data['id']]);
            }
        }

        $companyData = [
            'header_tabs' => $headerTabs,
            'professional_analysis_list' => $professionalAnalysisList ?? [],
            'name_recommend_list' => $nameRecommendList ?? [],
            'analysis_desc' => $analysisDesc ?? '',
        ];
        return [
            'personal_data' => null,
            'type' => 2,
            'company_data' => $companyData,
            'btn_data' => $btnData ?? null,
            'status' => $status,
            'unlock_data' => $this->getUnlockDataCompany($data['params']),
        ];
    }

    public function getUnlockDataPersonal(array $params)
    {
        $sexTxt = $params['sex'] == 1 ? '男生' : '女生';
        $bornTxt = $params['is_born'] ? '已出生' : '未出生';
        $list1 = [
            [
                'title' => '购买类型',
                'value_list' => ['个人起名', $bornTxt],
                'value_style' => 2,    //  值显示样式 1=>文本 2=>按钮样式
            ], [
                'title' => '档案信息',
                'value_list' => ['出生时间' . $params['recode_birth_date']],
                'value_style' => 2,    //  值显示样式 1=>文本 2=>按钮样式
            ], [
                'title' => '姓氏',
                'value_list' => [$params['surname']],
                'value_style' => 2,    //  值显示样式 1=>文本 2=>按钮样式
            ], [
                'title' => '性别',
                'value_list' => [$sexTxt],
                'value_style' => 2,    //  值显示样式 1=>文本 2=>按钮样式
            ], [
                'title' => '起名字数',
                'value_list' => ["{$params['num']}个字"],
                'value_style' => 2,    //  值显示样式 1=>文本 2=>按钮样式
            ],
        ];

        $list2 = [];
        if ($params['num'] > 2 && $params['type'])
        {
            $t1 = $params['type'] == 1 ? '中位字' : '末位字';
            $list2[] = [
                'title' => '设置中位字',
                'value_list' => [$t1, $params['text']],
                'value_style' => 2,    //  值显示样式 1=>文本 2=>按钮样式
            ];
        }
        if ($params['remark'])
        {
            $list2[] = [
                'title' => '特殊要求',
                'value_list' => [$params['remark']],
                'value_style' => 1,    //  值显示样式 1=>文本 2=>按钮样式
            ];
        }
        return [
            'list1' => $list1,
            'list2' => $list2,
        ];
    }

    public function getUnlockDataCompany(array $params)
    {
        $recodeList = [];
        foreach ($params['originator_data'] as $item)
        {
            $recodeList[] = sprintf('%s %s', $item['name'], $item['birth_date'] ?? '');
        }
        $list1 = [
            [
                'title' => '购买类型',
                'value_list' => ['公司起名'],
                'value_style' => 2,    //  值显示样式 1=>文本 2=>按钮样式
            ], [
                'title' => '档案信息',
                'value_list' => $recodeList,
                'value_style' => 2,    //  值显示样式 1=>文本 2=>按钮样式
            ], [
                'title' => '公司开业信息',
                'value_list' => [$params['c_birth_date'] ?? ''],
                'value_style' => 2,    //  值显示样式 1=>文本 2=>按钮样式
            ],
        ];
        $list2 = [
            [
                'title' => '公司主营业务',
                'value_list' => [$params['business']],
                'value_style' => 1,    //  值显示样式 1=>文本 2=>按钮样式
            ], [
                'title' => '特殊要求',
                'value_list' => [$params['remark']],
                'value_style' => 1,    //  值显示样式 1=>文本 2=>按钮样式
            ],
        ];
        return [
            'list1' => $list1,
            'list2' => $list2,
        ];
    }
}